<template>
  <md-nav-bar title="mv详情" color="white" backgroundColor="#2B2A2A" />
  <view class="mv-detail-container">
    <!-- 视频播放器 -->
    <view class="video-container" v-if="!!mvDetail">
      <view v-if="mvDetail.status === 0 || mvDetail.status === 1">
        <text>合成中</text>
      </view>
      <view v-if="mvDetail.status === 2">
        <video
            :src="mvDetail.mvUrl"
            class="mv-video"
            controls
            style="width: 90vw; height: 75vh;border-radius: 24rpx;"
        />
      </view>
      <view v-if="mvDetail.status === 3 || mvDetail.status === 4">
        <text>合成失败</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <button class="action-btn home-btn" @click="backHome">
        <text>回首页</text>
      </button>

      <template v-if="mvDetail && mvDetail.memberId === auth.userId ">
        <button class="action-btn setting-btn" @click="setting" v-if="mvDetail.status === 2">
          <text>公开</text>
        </button>

        <button class="action-btn download-btn" @click="handleDownload" v-if="mvDetail.status === 2">
          <text>下载</text>
        </button>

        <button class="action-btn delete-btn" @click="handleDelete"  v-if="mvDetail.status === 2 || mvDetail.status === 3 || mvDetail.status === 4">
          <text>删除</text>
        </button>
      </template>
    </view>
  </view>
  <uni-popup ref="modal" type="bottom" safeArea backgroundColor="#fff">
    <view class="modal-style">
      <uni-title type="h1" title="设置" />
      <uni-forms ref="form" :modelValue="data.formData" label-position="left" label-width="150px">
        <!-- 是否发布到广场 -->
        <uni-forms-item label="发布到MV广场:" name="isShowVideo">
          <uni-data-checkbox v-model="data.formData.isShowVideo" :localdata="data.options" />
        </uni-forms-item>
      </uni-forms>
      <view class="modal-btn">
        <view class="btn" @click="handleCancel">取消</view>
        <view class="btn" @click="handleSubmit">提交</view>
      </view>
    </view>
  </uni-popup>
</template>

<script lang="ts" setup>
import {onLoad, onShareAppMessage, onShareTimeline} from '@dcloudio/uni-app';
import {computed, reactive, ref} from "vue";
import API from "@/api";
import api from "@/api";

const data = reactive({
  id: null,
  formData: {},
  rules: {},
  options: [
    {
      text: '是',
      value: 1,
    },
    {
      text: '否',
      value: 0,
    },
  ],
});
const modal = ref<any>(null);
const form = ref(null);
// MV详情数据
const mvDetail = ref<any>(null);
const mvId = ref<string | null>(null);
const auth = uni.getStorageSync('auth')
// const canEdit = computed(() => {
//   return mvDetail.value && mvDetail.value.memberId === auth.userId ;
// })

// 页面加载时获取参数
onLoad((options) => {
  if (options && options.id) {

    mvId.value = options.id;
    fetchMvDetail(options.id);
  }
  const auth = uni.getStorageSync('auth');
  data.userId = auth?.userId;
});

// 获取MV详情
const fetchMvDetail = async (id: string) => {
  try {
    const result = await API.Mv.get(id);
    mvDetail.value = result.data;
    data.formData.isShowVideo = mvDetail.value.isShowVideo
  } catch (error) {
    console.error('获取MV详情失败:', error);
    uni.showToast({
      title: '获取MV详情失败',
      icon: 'none'
    });
  }
};

// 删除功能
const handleDelete = () => {
  if (!mvId.value) return;

  uni.showModal({
    title: '确认删除',
    content: '确定要删除这个MV吗？',
    success: async (res) => {
      if (res.confirm) {
        // 执行删除操作
        // 这里可以调用删除API
        await api.Mv.delete(mvId.value)
        await uni.showToast({
          title: '删除成功',
          icon: 'success'
        });
        // 删除完成后返回上一页
        uni.navigateBack();
      }
    }
  });
};

const backHome = () => {
  uni.reLaunch({
    url: '/pages/index/index',
  });
}

const handleDownload = () => {
  if (!mvDetail.value) return;
  uni.showLoading({
    title: '下载中...'
  });
  // 调用uni-app下载功能
  uni.downloadFile({
    url: mvDetail.value.mvUrl,
    success: (res) => {
      if (res.statusCode === 200) {
        // 保存到本地
        uni.saveFile({
          tempFilePath: res.tempFilePath,
          success: (savedRes) => {
            console.log('视频保存成功', savedRes.savedFilePath);
            uni.showToast({ title: '下载成功' });

            uni.saveVideoToPhotosAlbum({
              filePath: savedRes.savedFilePath,
              success: () => {
                uni.showToast({
                  title: '已保存到相册',
                  icon: 'success'
                });
              },
              fail: (err) => {
                console.error('保存到相册失败', err);
                // 如果保存到相册失败，提示用户文件已保存在临时路径
                uni.showToast({
                  title: '下载失败',
                  icon: 'none'
                });
              }
            });
          },
          fail: (err) => {
            console.error('保存失败', err);
          },
          complete: () => {
            uni.hideLoading();
          }
        });
      }
    },
    fail: (err) => {
      console.error('下载失败', err);
      uni.showToast({ title: '下载失败', icon: 'none' });
    }
  });
}

const setting = () => {
  modal.value?.open();
}

const handleCancel = () => {
  modal.value?.close();
};

const handleSubmit = async () => {
  try {
    const res = await form.value?.validate();
    // 处理提交格式
    const values = {
      isShowVideo: res?.isShowVideo,
      videoId: Number(mvId.value),
    };
    await api.Mv.update(values);
    uni.showModal({
      title: '提示',
      content: '修改成功',
      showCancel: false,
      success: res => {
        if (res.confirm) {
          handleCancel();
          fetchMvDetail(Number(mvId.value));
        }
      },
    });
  } catch (error) {}
};

onShareAppMessage(res => {
  return {
    title: '【mv作品】' + mvDetail.value.musicName,
    imageUrl: mvDetail.value.coverUrl || 'https://cdn.xmxiaomai.com/isong_static/share.jpg',
    path: '/pages/sub/mv/detail?id=' + (mvDetail.value.videoId || '') + (data.userId ? ('&parentId=' + data.userId) : ''),
  };
});

onShareTimeline(() => {
  return {
    title: '【mv作品】' + mvDetail.value.musicName,
    imageUrl: mvDetail.value.coverUrl || 'https://cdn.xmxiaomai.com/isong_static/share.jpg',
    query: 'id=' + mvDetail.value.videoId + (data.userId ? ('&parentId=' + data.userId) : ''),
  };
});
</script>

<style lang="scss" scoped>
.mv-detail-container {
  min-height: 100vh;
  background: #2b2a2a;
  color: #fff;
  padding-bottom: 64rpx;
  box-sizing: border-box;
  padding-top: 32rpx;
}

.video-container {
  width: 100%;
  height: 75vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #2b2a2a;
  border-radius: 24rpx;
}

.mv-video {
  width: 100%;
  height: 100%;
}

.bottom-actions {
  position: fixed;
  bottom: 90rpx;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  padding: 0 40rpx;
  gap: 20rpx;
  z-index: 10;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: rgba(0, 0, 0, 0.5);
  border: none;
  border-radius: 50rpx;
  //padding: 20rpx 30rpx;
  width: 24%;
  color: #fff;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;

  &::after {
    border: none;
  }
}

.home-btn {
  background-color: rgba(0, 122, 255, 0.7);
}

.setting-btn {
  background-color: rgba(255, 166, 0, 0.7);
}

.download-btn {
  background-color: rgb(40, 131, 12);
}

.delete-btn {
  background-color: rgba(255, 59, 48, 0.7);
}

.iconfont {
  font-size: 40rpx;
  margin-bottom: 10rpx;
}

.modal-style {
  height: 30vh;
  padding: 24rpx;
  box-sizing: border-box;
  width: 100%;

  .modal-btn {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 20rpx;
    padding: 0 40rpx;
    margin-top: 80rpx;

    & > .btn {
      height: 80rpx;
      width: 40%;
      line-height: 80rpx;
      text-align: center;
      border-radius: 10rpx;
      border: 1rpx solid #ddd;
      padding: 0 16rpx;
      box-sizing: border-box;
      &:last-of-type {
        background: #01604a;
        color: white;
        border: 0;
      }
    }
  }
}
</style>

